<?php

class          Common_DataTable_Model_Array 
    extends    Common_DataTable_Model_Abstract 
    implements Common_DataTable_Model_SelfDefining,
               Common_DataTable_Model_Sortable,
               Common_DataTable_Model_Groupable
{

    protected $arr_data = null;
    
    public function __construct($arr_data) {
        
        parent::__construct();
        
        $this->__addMixin(new Common_DataTable_Model_Mixin_GroupMeta(), 'group');
        $this->__addMixin(new Common_DataTable_Model_Mixin_HeaderDetector(), 'detector');
        
        $this->setData($arr_data);
        
    }
    
    public function countData() {
        
        // default value; use null because it could be treated like zero in 
        // client scripts using the empty() function
        $int_count = null;
        
        // case: the data count has already been calculated
        if(is_array($this->arr_data)) {
            $int_count = count($this->arr_data);
        }
        
        return $int_count;
    }
    
    public function getData($int_size = null, $int_offset = null) {
        
        $int_data_count = $this->countData();
        
        $arr_data = $this->getRawData($int_size, $int_offset);
        
        $arr_data = $this->group__generateDataGroups($arr_data);
        
        $arr_output = array_merge(array(
            'count' => $int_data_count
        ), $arr_data);
        
        return $arr_output;
    }
    
    
    protected function getRawData($int_size = null, $int_offset = null) {
        
        if(is_integer($int_size) && is_integer($int_offset)) {
            $arr_data = array_slice($this->arr_data, $int_offset, $int_size, true);
        } else {
            $arr_data = $this->arr_data;
        }
        
        return $arr_data;
    }
    
    public function setData($arr_data) {
        if(is_array($arr_data)) {
            $this->arr_data = $arr_data;
        }
    }

    public function hasData() {
        return !empty($this->arr_data);
    }
    
    public function sortDataBy($arr_sort_meta) {
        
        $arr_data = $this->getRawData();
        
        Utility_SortFunctions::sort($arr_data, $arr_sort_meta);

        $this->setData($arr_data);
        
    }
    
    public function groupDataBy($arr_group_meta) {
        $this->group__groupDataBy($arr_group_meta);
    }
    
    public function defineHeaders() {
        
        $arr_headers = null;
        
        if($this->hasData()) {
            
            $arr_data = $this->getRawData();
            $arr_first = reset($arr_data);
            
            if(is_array($arr_first)) {
                $arr_headers = $this->detectHeaders($arr_first);
            }
            
        }
        
        return $arr_headers;
    }
    
    public function toArray()
    {
        return $this->arr_data;
    }
    
}
